﻿using System;
using System.Collections.ObjectModel;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
using Automator.Tasks.Core;
using Automator.Tasks.Windows;

namespace Automator.Tasks
{
    /// <summary>
    /// Class that compares WorkflowExecutionContext.Result with user-defined value
    /// Defined attributes:
    /// EstimatedResult: Value for comparison
    /// </summary>
    public class SwitchResultTask: Task, ITaskExecutable
    {
        public void Execute(WorkflowExecutionContext context)
        {
            if (context.Argument == null)
                throw new TaskConditionException("Execution context argument is null");
            else if (!context.Argument.ToString().Equals(
                context.DereferenceVariables(this.Attributes["EstimatedResult"].Value)
               ))
                throw new TaskConditionException(String.Format("{0} != {1}", context.Argument.ToString(),
                                                               context.DereferenceVariables(this.Attributes["EstimatedResult"].Value)));
        }
        
        public SwitchResultTask():
            base()
        {
            this.Title = "Switch Result";
            this.Description = "Compare parent result with specified value";
            this.TaskImage = new BitmapImage(new Uri("/Automator.Tasks;component/Resources/switchresult.png", UriKind.Relative));

            this.Attributes.Add(new TaskAttributeDefinition() { Key = "EstimatedResult", Value = String.Empty });
        }
        
        public override string CommandText
        {
            get { return Attributes["EstimatedResult"].Value.ToString().Trim(); }
            set { base.CommandText = value; }
        }
        
        public override bool EditTask()
        {
            base.EditTask();
            SwitchResultTaskEditWindow window = new SwitchResultTaskEditWindow();
            window.Owner = Application.Current.MainWindow;
            window.Title = String.Format("Edit {0} Task", this.Title);
            //performing binding to the header
            window.header.ContentPanel.DataContext = this;

            window.edtEstimatedResult.Text = this.Attributes["EstimatedResult"].Value.ToString();
            window.footer.BtnOK.Click += delegate { window.DialogResult = true; };

            if (window.ShowDialog() == true)
            {
                this.Attributes["EstimatedResult"].Value = window.edtEstimatedResult.Text.Trim();
                
                this.CommandText = String.Empty;
                return true;
            }
            else return false;
        }
    }
}